import axios from 'axios';
import * as constants from './constants';

const changeDetail = (data) => ({
  type: constants.GET_WORKDATA,
  workData: data
});

// 初始加载获取WorksTablePlus所需数据 workData
export const getWorksData = () => {
  return (dispatch) => {
    axios.get('http://localhost:9080/work/all?start=0&length=10', {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      console.log(res.data.data);
      dispatch(changeDetail(res.data.data));
    }).catch(() => {
      console.log('error');
    })
  }
};

// enabled part
export const changeEnabled = (checked, id) => {
  let checkedNum = checked ? 1: 0;
  return () => {
    axios.get('http://localhost:9080/work/update-admin?enabled='+checkedNum+'&workId='+id, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      alert('设置成功！');
    }).catch(()=>{
      alert('error');
    })
  }
};

// search part
export const searchFormChange = (value) => ({
  type: constants.SEARCHFORM_CHANGE,
  authorName: value.authorName
});

export const searchWorkByAuthor = (authorName) => {
  return (dispatch) => {
    axios.get('http://localhost:9080/work/search?start=0&length=10&authorName='+authorName, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      if(res.data == '') {
        alert('未搜索到结果');
      }else {
        console.log(res.data.data);
        dispatch(changeDetail(res.data.data));
      }
    }).catch(()=>{
      console.log('error');
    })
  }
}